import { Injectable } from '@nestjs/common';
import { DeepPartial, FindOneOptions, Repository } from 'typeorm';

@Injectable()
export class CommonService<T extends object> {
  private readonly mainRepository: Repository<T>;
  constructor(mainRepository: Repository<T>) {
    this.mainRepository = mainRepository;
  }

  async findAll() {
    return await this.mainRepository.find();
  }

  async findOneBy(whereOption: DeepPartial<T> | DeepPartial<T>[]) {
    return await this.mainRepository.findOneBy(whereOption);
  }

  // 创建
  async create(params: DeepPartial<T>) {
    return await this.mainRepository.save(params);
  }

  async delete(params: DeepPartial<T>) {
    return await this.mainRepository.delete(params);
  }

  async update(
    where: FindOneOptions['where'] & DeepPartial<T>,
    params: DeepPartial<T>,
  ) {
    const targetEntity = await this.mainRepository.findOne({
      where: where,
    });
    if (targetEntity) {
      Object.assign(targetEntity, params);
      return await this.mainRepository.save(targetEntity as DeepPartial<T>);
    } else {
      Object.assign(params, where);
      return await this.mainRepository.save(params);
    }
  }
}
